package com.vilen.learn.java7.V4.V4_3_5;

import com.vilen.learn.java7.V4.Update;

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by vilen on 2017/10/2.
 */
public class MicroBlogTimeline {
    private final CopyOnWriteArrayList<Update> updates;
    private final Lock lock;
    private final String name;
    private Iterator<Update> it;

    MicroBlogTimeline(String name_, CopyOnWriteArrayList<Update> l_, Lock lock_) {
        name = name_;
        updates = l_;
        lock = lock_;
    }

    public MicroBlogTimeline(String name) {
        this.name = name;
        updates = new CopyOnWriteArrayList<>();
        lock = new ReentrantLock();
    }

    public void addUpdate(Update update_) {
        updates.add(update_);
    }
    //设置迭代器
    public void prep() {
        it = updates.iterator();
    }

    public void printTimeline() {
        //需要在这里锁定
        lock.lock();
        try{
            if (it != null) {
                System.out.println(name + ": ");
                while (it.hasNext()) {
                    Update s = it.next();
                    System.out.println(s+", ");
                }
                System.out.println();
            }
        }finally {
            lock.unlock();
        }
    }
}
